package com.cskaoyan.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author rebaogu
 * @description 自定义的一个认证器
 * @date 2022.04.11 12:55
 * @package com.cskaoyan.shiro
 * @Classname CustomAuthenticator
 */

public class CustomAuthenticator extends ModularRealmAuthenticator {

    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        assertRealmsConfigured();

        Collection<Realm> originRealms = getRealms();
        MallToken token = (MallToken) authenticationToken;
        // 获取type类型
        String type = token.getType();
        // 将realm依次进行遍历,如果type属于admin 则--> adminRealm 如果属于wx --> wxRealm

        ArrayList<Realm> realmArrayList = new ArrayList<>();

        for (Realm originRealm : originRealms) {
            if (originRealm.getName().toLowerCase().contains(type)) {
                realmArrayList.add(originRealm);
            }
        }

        // 将分发后的返回给
        //return realmArrayList.size() == 1 ? this.doSingleRealmAuthentication((Realm)realmArrayList.iterator().next(), authenticationToken) : this.doMultiRealmAuthentication(realmArrayList, authenticationToken);

        if (realmArrayList.size() == 1) {
            return doSingleRealmAuthentication(realmArrayList.iterator().next(), authenticationToken);
        } else {
            return doMultiRealmAuthentication(realmArrayList, authenticationToken);
        }
    }
}
